// 设置项组件
// 通用的设置项渲染组件，支持不同类型的设置控件

import React, { useState } from 'react';
import { RotateCcw, Info } from 'lucide-react';
import { BaseSetting, SettingType } from '../../../types/settings';
import { useSettingsStore } from '../../../stores/settingsStore';
import { SettingPreview } from './SettingPreview';

interface SettingItemProps {
  setting: BaseSetting;
  showDescription?: boolean;
  highlightQuery?: string;
}

export const SettingItem: React.FC<SettingItemProps> = ({
  setting,
  showDescription = true,
  highlightQuery
}) => {
  const { getSetting, setSetting, resetSetting } = useSettingsStore();
  const [showTooltip, setShowTooltip] = useState(false);
  const [previewValue, setPreviewValue] = useState<any>(null);

  const currentValue = getSetting(setting.id) ?? setting.currentValue;

  // 处理值变化
  const handleValueChange = (newValue: any) => {
    setSetting(setting.id, newValue);
    setPreviewValue(newValue);
  };

  // 重置设置
  const handleReset = () => {
    resetSetting(setting.id);
  };

  // 高亮匹配文本
  const highlightText = (text: string) => {
    if (!highlightQuery) return text;
    
    const regex = new RegExp(`(${highlightQuery})`, 'gi');
    const parts = text.split(regex);
    
    return parts.map((part, index) => 
      regex.test(part) ? (
        <mark key={index} className="bg-yellow-200 dark:bg-yellow-800">
          {part}
        </mark>
      ) : part
    );
  };

  // 渲染控件
  const renderControl = () => {
    switch (setting.type) {
      case SettingType.Boolean:
        return (
          <label className="flex items-center cursor-pointer">
            <input
              type="checkbox"
              checked={currentValue}
              onChange={(e) => handleValueChange(e.target.checked)}
              disabled={setting.readonly}
              className="sr-only"
            />
            <div className={`
              relative w-11 h-6 rounded-full transition-colors
              ${currentValue 
                ? 'bg-blue-600' 
                : 'bg-gray-300 dark:bg-gray-600'
              }
              ${setting.readonly ? 'opacity-50 cursor-not-allowed' : ''}
            `}>
              <div className={`
                absolute top-0.5 left-0.5 w-5 h-5 bg-white rounded-full transition-transform
                ${currentValue ? 'translate-x-5' : 'translate-x-0'}
              `} />
            </div>
          </label>
        );

      case SettingType.Number:
        return (
          <input
            type="number"
            value={currentValue}
            onChange={(e) => handleValueChange(Number(e.target.value))}
            min={setting.validation?.min}
            max={setting.validation?.max}
            disabled={setting.readonly}
            className="w-24 px-3 py-1 border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white disabled:opacity-50"
          />
        );

      case SettingType.String:
        return (
          <input
            type="text"
            value={currentValue}
            onChange={(e) => handleValueChange(e.target.value)}
            disabled={setting.readonly}
            className="flex-1 max-w-xs px-3 py-1 border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white disabled:opacity-50"
          />
        );

      case SettingType.Select:
        return (
          <select
            value={currentValue}
            onChange={(e) => handleValueChange(e.target.value)}
            disabled={setting.readonly}
            className="px-3 py-1 border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white disabled:opacity-50"
          >
            {setting.validation?.options?.map((option) => (
              <option key={option.value} value={option.value}>
                {option.label}
              </option>
            ))}
          </select>
        );

      case SettingType.Color:
        return (
          <div className="flex items-center space-x-2">
            <input
              type="color"
              value={currentValue}
              onChange={(e) => handleValueChange(e.target.value)}
              disabled={setting.readonly}
              className="w-8 h-8 border border-gray-300 dark:border-gray-600 rounded cursor-pointer disabled:opacity-50"
            />
            <input
              type="text"
              value={currentValue}
              onChange={(e) => handleValueChange(e.target.value)}
              disabled={setting.readonly}
              className="w-20 px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white disabled:opacity-50"
            />
          </div>
        );

      case SettingType.Font:
        return (
          <select
            value={currentValue}
            onChange={(e) => handleValueChange(e.target.value)}
            disabled={setting.readonly}
            className="px-3 py-1 border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white disabled:opacity-50"
            style={{ fontFamily: currentValue }}
          >
            <option value="Consolas, 'Courier New', monospace">Consolas</option>
            <option value="'Fira Code', monospace">Fira Code</option>
            <option value="'Source Code Pro', monospace">Source Code Pro</option>
            <option value="Monaco, monospace">Monaco</option>
            <option value="'JetBrains Mono', monospace">JetBrains Mono</option>
          </select>
        );

      default:
        return (
          <span className="text-gray-500 dark:text-gray-400">
            不支持的设置类型
          </span>
        );
    }
  };

  const isModified = currentValue !== setting.defaultValue;

  return (
    <div className="space-y-3">
      <div className="flex items-start justify-between py-3 group">
      <div className="flex-1 min-w-0 mr-4">
        <div className="flex items-center space-x-2">
          <h4 className="font-medium text-gray-900 dark:text-white">
            {highlightText(setting.name)}
          </h4>
          {setting.requiresRestart && (
            <span className="text-xs px-2 py-0.5 bg-orange-100 dark:bg-orange-900 text-orange-800 dark:text-orange-200 rounded">
              需要重启
            </span>
          )}
          {isModified && (
            <span className="text-xs px-2 py-0.5 bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-200 rounded">
              已修改
            </span>
          )}
        </div>
        
        {showDescription && (
          <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
            {highlightText(setting.description)}
          </p>
        )}
        
        {setting.tags && setting.tags.length > 0 && (
          <div className="flex flex-wrap gap-1 mt-2">
            {setting.tags.map((tag) => (
              <span
                key={tag}
                className="text-xs px-1.5 py-0.5 bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400 rounded"
              >
                {tag}
              </span>
            ))}
          </div>
        )}
      </div>

      <div className="flex items-center space-x-2">
        {renderControl()}
        
        {isModified && (
          <button
            onClick={handleReset}
            className="p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 opacity-0 group-hover:opacity-100 transition-opacity"
            title="重置为默认值"
          >
            <RotateCcw className="w-4 h-4" />
          </button>
        )}
        
        <div className="relative">
          <button
            onMouseEnter={() => setShowTooltip(true)}
            onMouseLeave={() => setShowTooltip(false)}
            className="p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
          >
            <Info className="w-4 h-4" />
          </button>
          
          {showTooltip && (
            <div className="absolute right-0 top-8 w-64 p-3 bg-gray-900 dark:bg-gray-700 text-white text-sm rounded-lg shadow-lg z-10">
              <div className="font-medium mb-1">{setting.name}</div>
              <div className="text-gray-300 dark:text-gray-400 mb-2">
                {setting.description}
              </div>
              <div className="text-xs text-gray-400">
                默认值: {String(setting.defaultValue)}
              </div>
              {setting.validation && (
                <div className="text-xs text-gray-400 mt-1">
                  {setting.validation.min !== undefined && `最小值: ${setting.validation.min}`}
                  {setting.validation.max !== undefined && ` 最大值: ${setting.validation.max}`}
                </div>
              )}
            </div>
          )}
        </div>
      </div>

      {/* 设置预览 */}
      {previewValue !== null && (
        <SettingPreview
          setting={setting}
          previewValue={previewValue}
          onPreviewToggle={(enabled) => {
            if (!enabled) {
              setPreviewValue(null);
            }
          }}
        />
      )}
    </div>
    </div>
  );
};
